/*
 * @Author: Wilbur
 * @Date: 2019-03-27 10:05:49
 * @Last Modified by: Wilbur
 * @Last Modified time: 2019-03-29 17:36:19
 */
<template>
    <div class="container material-add-wrap">
        <el-form
            v-if="init"
            ref="mainform"
            :model="formData"
            label-position="right"
            status-icon
            :rules="formRule"
            label-width="110px"
            :disabled="false">
            <!-- 资料设置 -->
            <div class="form-unit">
                <div class="form-title">资料设置</div>
                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="tag_nos"
                    label="选择标签:">
                    <el-select
                        v-model="formData.tag_nos"
                        multiple
                        class="task-input"
                        placeholder="请选择">
                        <el-option
                            v-for="item in tagsList"
                            :key="item.tag_no"
                            :label="item.tag_name"
                            :value="item.tag_no"/>
                    </el-select>
                </el-form-item>

                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="material_path"
                    label="上传文件:">
                    <el-upload
                        class="upload-demo"
                        ref="upload"
                        action="https://jsonplaceholder.typicode.com/posts/"
                        :file-list="fileList"
                        :http-request="e=> {fnUploadFile(e, fileList)}"
                        :on-remove="e=>{fnUploadRemove(e, fileList)}"
                        :multiple="false">
                        <el-button
                            slot="trigger"
                            size="small"
                            type="primary">

                            <span v-if="material_no">重新上传</span>
                            <span v-if="!material_no">选取文件</span>
                        </el-button>
                        <!-- <el-button
                            type="success"
                            v-if="material_no">查看文件</el-button> -->
                        <div
                            slot="tip"
                            class="el-upload__tip">只能上传.rar .zip .doc .docx .pdf文件，且单个文件不超过200M</div>
                    </el-upload>
                </el-form-item>
                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="material_name"
                    label="文档名称:">
                    <el-input
                        placeholder="必填"
                        v-model="formData.material_name"
                        size="small"
                        class="task-input"/>
                </el-form-item>

                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="material_image"
                    label="文档封面:">

                    <el-upload
                        :show-file-list="false"
                        :http-request="e=> {fnUploadImageOfCustomerLogo(e)}"
                        accept="image/*"
                        class="upload-demo"
                        drag
                        action="https://jsonplaceholder.typicode.com/posts/">
                        <img
                            v-if="formData.material_image"
                            :src="formData.material_image"
                            class="avatar">
                        <i
                            class="el-icon-upload"
                            v-if="!formData.material_image"/>
                        <div
                            class="el-upload__text"
                            v-if="!formData.material_image">将文件拖到此处，或<em>点击上传</em></div>
                        <div
                            class="el-upload__tip"
                            slot="tip">只能上传jpg/png文件，且不超过500kb</div>
                    </el-upload>
                </el-form-item>

                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="material_info"
                    label="文档描述:">
                    <el-input
                        type="textarea"
                        :rows="5"
                        placeholder="必填"
                        v-model="formData.material_info"
                        size="small"
                        class="task-input"/>
                        <!-- <span style="display:inline-block;color:#999;margin-left:12px">*链接请包含http://</span> -->
                </el-form-item>

                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="material_level"
                    label="下载权限:">
                    <el-radio
                        v-model="formData.material_level"
                        :label="1">仅会员可下载</el-radio>
                    <el-radio
                        v-model="formData.material_level"
                        :label="0">所有人可下载</el-radio>
                </el-form-item>
            </div>

            <div class="form-unit">
                <div class="operate-baar">
                    <el-button
                        size="medium"
                        v-show="material_no ? false : true"
                        @click="fnReset()">重置</el-button>
                    <el-button
                        size="medium"
                        type="primary"
                        @click="fnSubmit()">提交</el-button>
                </div>
            </div>
        </el-form>
    </div>
</template>

<script>
export default {
    components: {},
    data() {
        return {
            fileList: [],
            tagsList: [],
            authResult: {},
            breadcrumbList: [
                {
                    title: "广告系统",
                },
                {
                    title: "资料库",
                    name: 'materialList',
                },
                {
                    title: '上传资料'
                }
            ],
            material_no: '',
            formData: {
                material_name: '',
                material_info: '',
                tag_nos: [],
                material_image: '',
                material_path: '',
                material_level: 1,
                material_sort: '',
                material_status: 1,
                material_file_name: '',
                material_size: ''
            },
            formRule: {
                tag_nos: [{
                    required: true, message: '请选择文档标签', trigger: 'change'
                }],
                material_path: [{
                    required: true, message: '请上传文件', trigger: 'change'
                }],
                material_name: [
                    { required: true, message: '请输入文档名称', trigger: 'blur' }
                ],
                material_image: [
                    { required: true, message: '请上传文档封面', trigger: 'change' }
                ],
                material_info: [
                    { required: true, message: '请填写文档标书', trigger: 'change' }
                ]
            },
            submitting: false,
            init: false,

            baseUrl: '',
            sessionTicket: localStorage.getItem('sessionTicket'),
            escape: escape,
        };
    },
    created() {
        this.authResult = this.$route.meta.authResult;
        this.$store.commit('SET_HEADER', this.breadcrumbList);

        this.material_no = this.$route.query.material_no ? this.$route.query.material_no : '';

        this.fnGetSelectTags();
        if (!this.material_no) {
            this.init = true;
        }else{
            this.fninitMaterialInfo();
        }
    },
    methods: {
        fninitMaterialInfo() {
            this.$post('/wei4/material%5Cget', {
                material_no: this.material_no
            }, resp => {
                if(resp.code == 1){
                    this.formData = {
                        ...resp.data,
                        tag_nos: resp.data.tag_no_list,
                        material_image: resp.data.material_image_list[0].url,
                        material_size: resp.data.material_size
                    };
                    this.fileList = [{name: this.formData.material_file_name, url: this.formData.material_path}];

                    this.init = true;
                }else{
                    this.$message({
                        type: 'warning',
                        message: resp.msg
                    });
                }
            });
        },
        fnGetSelectTags() {
            this.$post('/wei4/material_tag%5Cget_list_select', {
            }, resp => {
                if(resp.code == 1){
                    this.tagsList = resp.data.list;
                }else{
                    this.$message({
                        type: 'warning',
                        message: resp.msg
                    });
                }
            });
        },
        fnSubmit(){
            if(this.submitting){
                return ;
            }
            this.$refs.mainform.validate(valid => {
                if(valid){
                    this.submitting = true;

                    let data = {
                        material_name: this.formData.material_name,
                        material_info: this.formData.material_info,
                        material_tag_json: JSON.stringify(this.formData.tag_nos),
                        material_image_json: JSON.stringify([{"url":this.formData.material_image}]),
                        material_path: this.formData.material_path,
                        material_level: this.formData.material_level,
                        material_sort: 999,
                        material_status: this.formData.material_status,
                        material_file_name: this.formData.material_file_name,
                        material_size: this.formData.material_size
                    };

                    if(this.material_no){
                        data.material_no = this.material_no;

                        this.$post('/wei4/material%5Csave', data, resp => {
                            if(resp.code == 1){
                                this.$message({
                                    type: 'success',
                                    center: true,
                                    message: '修改成功'
                                });
                                // this.$refs.mainform.resetFields();
                                this.$router.push({
                                    name: 'materialList'
                                });
                            }else{
                                this.$message({
                                    type: 'warning',
                                    center: true,
                                    message: resp.msg
                                });
                            }
                            this.submitting = false;
                        });
                    }else{
                        this.$post('/wei4/material%5Csave', data, resp => {
                            if(resp.code == 1){
                                this.$message({
                                    type: 'success',
                                    center: true,
                                    message: '操作成功'
                                });
                                this.$router.push({
                                    name: 'materialList'
                                });
                            }else{
                                this.$message({
                                    type: 'warning',
                                    center: true,
                                    message: resp.msg
                                });
                            }
                            this.submitting = false;
                        });
                    }

                }
            });
        },
        fnUploadImage(e, success, error) {
            let timeTmp = new Date().getTime();
            let pic = new FormData();

            pic.append('file', e.file);
            this.$upload({
                url: '/__local/common%5Cupload',
                data: pic,
                progress: e.onProgress,
                success: resp => {
                    if (resp.code == 1) {
                        success(resp);
                    } else {
                        this.$message({
                            type: 'warning',
                            message: '上传图片失败',
                            center: true
                        });
                        error(resp);
                    }
                }
            });
        },
        fnUploadFilePost(e, json, success, error) {
            let timeTmp = new Date().getTime();
            let pic = new FormData();

            pic.append('policy', json.policy);
            pic.append('signature', json.signature);
            pic.append('file', e.file);

            this.$upload({
                url: json.api,
                data: pic,
                progress: e.onProgress,
                success: resp => {
                    if (resp.code == 200) {
                        success(resp);
                    } else {
                        this.$message({
                            type: 'warning',
                            message: '上传图片失败',
                            center: true
                        });
                        error(resp);
                    }
                }
            });
        },
        fnUploadImageOfCustomerLogo(e) {
            this.fnUploadImage(e, (resp) => {
                this.formData.material_image = resp.data.url;
            }, (resp) => {
                console.log(resp.msg);
            });
        },
        fnGetUploadAuth(name, callback) {
            this.$post('/wei4/material%5Cupload_auth', {
                file_name: name
            }, resp => {
                if(resp.code == 1){
                    callback(resp.data);
                }else{
                    this.$message({
                        type: 'warning',
                        message: resp.msg
                    });
                }
            });
        },
        fnUploadFile(e, fileList) {
            this.formData.material_name = e.file.name;
            this.formData.material_file_name = e.file.name;
            this.formData.material_size = e.file.size;
            this.fnGetUploadAuth(e.file.name, (data)=>{
                this.fnUploadFilePost(e, data, (resp) => {
                    this.formData.material_path = resp.url;
                }, (resp) => {
                    console.log(resp);
                });
            });

        },
        fnReset(){
            this.$refs.mainform.resetFields();
        },
        fnUploadFileChange(e) {
            this.$refs.upload.clearFiles();
        },
        fnUploadRemove(e, fileList) {
            this.fileList = [];
        }
    },
};
</script>

<style lang="less" scoped>
    .avatar{
        width: 100%;
        height: 100%;;
    }
    .margin-top{
        margin-top: 15px;
    }
    .material-add-wrap {
      background: #fff;
      margin: 15px;
      margin-bottom: 0;
      padding: 30px;
      overflow: auto;
    }
    .form-unit {
      margin-bottom: 40px;
    }
    .form-title {
      font-size: 16px;
      font-weight: 600;
      color: rgba(0, 0, 0, 0.85);
      line-height: 18px;
      padding: 0 10px;
      border-left: 2px solid #1890ff;
      margin-bottom: 20px;
    }
    .task-input {
      width: 435px !important;
    }
    input::-webkit-outer-spin-button,
    input::-webkit-inner-spin-button {
      -webkit-appearance: none;
    }
    input[type="number"] {
      -moz-appearance: textfield;
    }

    .operate-baar {
      width: 100%;
      text-align: center;
      margin-top: 168px;
    }
</style>
<style lang="less">
.upload-demo .el-upload-list{
    max-width: 435px!important;
    li{
        display: none;
        &:first-child{
            margin-top: 0;
        }
        margin-bottom: 5px;
        &:last-child {
            display: inline-block;
        }
    }
}
</style>
